package com.yuxinmuyu.sports_management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuxinmuyu.sports_management.bean.dto.ExportSportsProjectDTO;
import com.yuxinmuyu.sports_management.bean.dto.ExportSportsScoreDTO;
import com.yuxinmuyu.sports_management.bean.entiy.SportsApply;
import com.yuxinmuyu.sports_management.bean.entiy.SportsProject;
import com.yuxinmuyu.sports_management.bean.entiy.SportsScore;
import com.yuxinmuyu.sports_management.bean.request.GetSportsScoreIDRequest;
import com.yuxinmuyu.sports_management.bean.request.GetSportsScoreInfoRequest;
import com.yuxinmuyu.sports_management.bean.request.GetSportsScoreRequest;
import com.yuxinmuyu.sports_management.bean.response.GetSportsScoreResponse;
import com.yuxinmuyu.sports_management.exception.BusinessException;
import com.yuxinmuyu.sports_management.mapper.SportsApplyMapper;
import com.yuxinmuyu.sports_management.mapper.SportsScoreMapper;
import com.yuxinmuyu.sports_management.service.SportsScoreService;
import com.yuxinmuyu.sports_management.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class SportsScoreServiceImpl implements SportsScoreService {
    @Resource
    private SportsScoreMapper sportsScoreMapper;

    @Resource
    private SportsApplyMapper sportsApplyMapper;

    @Transactional( rollbackFor = Exception.class)
    @Override
    public void addSportsScore(GetSportsScoreRequest request) {
        SportsScore score = sportsScoreMapper.getByID(request.getSportsID(),request.getUserID(),request.getYearTermID());
        if(Objects.nonNull(score)){
            throw new BusinessException("已存在该成绩信息!");
        }
        int n =sportsScoreMapper.insert(new SportsScore(null,request.getYearTermID(),request.getSportsID(),request.getUserID(),new Date()
                ,UserUtil.getUserName(),request.getScore(),request.isAwardsFlag(),request.getAwardsName()));
        if (n==0){
            throw new BusinessException("添加失败！");
        }
        n=sportsApplyMapper.update(null,Wrappers.<SportsApply>lambdaUpdate()
                .eq(SportsApply::getSportsID,request.getSportsID())
                .eq(SportsApply::getUserID,request.getUserID())
                .eq(!StringUtils.isBlank(request.getYearTermID()),SportsApply::getYearTermID,request.getYearTermID())
                .set(SportsApply::getFlag,3));
        if (n==0){
            throw new BusinessException("添加失败！");
        }
    }

    @Transactional( rollbackFor = Exception.class)
    @Override
    public void deleteSportsScore(GetSportsScoreIDRequest request) {
        int n = sportsScoreMapper.deleteById(request.getScoreID());
        if (n==0){
            throw new BusinessException("删除失败！");
        }
    }

    @Transactional( rollbackFor = Exception.class)
    @Override
    public void updateSportsScore(SportsScore sportsScore) {
        int n = sportsScoreMapper.update(null, Wrappers.<SportsScore>lambdaUpdate().eq(
                                SportsScore::getScoreID,sportsScore.getScoreID())
                .set(SportsScore::getYearTermID,sportsScore.getYearTermID())
                .set(SportsScore::getSportsID,sportsScore.getSportsID())
                .set(SportsScore::getUserID,sportsScore.getUserID())
                .set(SportsScore::getLastDate,new Date())
                .set(SportsScore::getOperator,UserUtil.getUserName())
                .set(SportsScore::getAwardsName,sportsScore.getAwardsName())
        );
        if (n==0){
            throw new BusinessException("更新失败！");
        }
    }

    @Override
    public Page<GetSportsScoreResponse> selectSportsScore(GetSportsScoreInfoRequest request) {
        Page<GetSportsScoreResponse> page = new Page<>(request.getCurrentPage(),request.getPageSize());
        page = sportsScoreMapper.selectSportsScore(page,request.getYearTermID(),request.getKeyword(), request.getDeptID(),request.getSportsID());
        return page;
    }

    @Override
    public void export(GetSportsScoreInfoRequest request, HttpServletResponse response) {
        Page<GetSportsScoreResponse> page = new Page<>(1,-1);
        page = sportsScoreMapper.selectSportsScore(page,request.getYearTermID(),request.getKeyword(), request.getDeptID(),request.getSportsID());
        try {
            List<GetSportsScoreResponse> list=page.getRecords();
            if(list.isEmpty()){
                throw new BusinessException("不存在数据！");
            }
            List<ExportSportsScoreDTO>exportList=new ArrayList<>();
            list.forEach(n->{
                ExportSportsScoreDTO dto=new ExportSportsScoreDTO();
                BeanUtil.copyProperties(n,dto);
                if(n.getType().equals(1)){
                    dto.setType("个人项目");
                }
                if(n.getType().equals(2)){
                    dto.setType("团队项目");
                }
                exportList.add(dto);
            });
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String currentTime = sdf.format(new Date());
            String originalFileName = "比赛成绩名单";
            String fileName = URLEncoder.encode(originalFileName + "_" + currentTime, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportSportsScoreDTO.class).sheet("1").doWrite(exportList);
        }catch (IOException e){
            throw new BusinessException("导出失败！");
        }
    }
}
